<?php
// +----------------------------------------------------------------------
// | Description: 框架基本 公共模型,所有模型都可继承此模型，基于RESTFUL CRUD操作
// +----------------------------------------------------------------------
// | Author: orchief
// +----------------------------------------------------------------------

namespace App\Common;

use think\Model as CommonModel;
use Utility\Db\DataList;

class Model extends CommonModel
{
    use DataList;
    protected $pk = 'id';
    protected $param;
    protected $map = [];
    protected $orderByString = ''; // 排序规则
    protected $specialConditions; // 特殊条件 
    protected $fuzzyConditions = null;
    protected $clearConditions = null; // 精确查询字段
    protected $returnFields = '';
    protected $rangeConditions = null;
    protected $union_fuzzyConditions = null;
    protected $foreignConditions = null;
    protected $page = 1;
    protected $limit = 20;

    /**
     * 解析搜索条件
     */
    public function getDataList($param)
    {
        $this->param = $param;
        if (isset($this->param['page'])) {
            $this->page = $this->param['page'];
        }
        if (isset($this->param['limit'])) {
            $this->limit = $this->param['limit'];
        }
        if (isset($this->param['orderByString'])) {
            $this->orderByString = $this->param['orderByString'];
        }
       
        // 数据
        $Model = $this;
        $Model = $this->parseParam($Model);
        $Model = $Model->field($this->returnFields);
        if ($this->limit != -1) {
            $Model = $Model->page($this->page, $this->limit);
        }
        $resData = $Model->select();
        // 数量
        $Model = $this;
        $Model = $this->parseParam($Model);
        $dataCount = $Model->count();
        $data['list'] = $resData;
        $data['dataCount'] = $dataCount;
        return $this->filter($data);
    }



    /**
     * 过滤
     *
     * @return void
     */
    public function filter($data)
    {
        return $data;
    }

    /**
     * [getDataById 根据主键获取详情]
     * @linchuangbin
     * @DateTime  2017-02-10T21:16:34+0800
     * @param     string                   $id [主键]
     * @return    [array]
     */
    public function getDataById($id = '')
    {
        $data = $this->get($id);
        if (!$data) {
            $this->error = '暂无此数据';
            return false;
        }
        return $data;
    }

    /**
     * [createData 新建]
     * @linchuangbin
     * @DateTime  2017-02-10T21:19:06+0800
     * @param     array                    $param [description]
     * @return    [array]                         [description]
     */
    public function createData($param, $fields=true)
    {
        // 验证
        $validateName = 'App\\Validate\\'.$this->convertUnderline($this->name);
        $validate = new $validateName();
        if (!$validate->scene('Create')->check($param)) {
            $this->error = $validate->getError();
            return false;
        }
        try {
            $this->data($param)->allowField($fields)->save();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
    }

    /**
     * 通过id修改用户
     * @param  array   $param  [description]
     */
    public function updateDataById($param, $id, $fields = true, $pk = 'id')
    {
        try {
            $this->allowField($fields)->save($param, [$pk => $id]);
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
    }

    /**
     * [delDataById 根据id删除数据]
     * @linchuangbin
     * @DateTime  2017-02-11T20:57:55+0800
     * @param     string                   $id     [主键]
     * @param     boolean                  $delSon [是否删除子孙数据]
     * @return    [type]                           [description]
     */
    public function delDataById($id = '', $delSon = false)
    {
        $this->startTrans();
        try {
            $this->where($this->getPk(), $id)->delete();
            if ($delSon && is_numeric($id)) {
                // 删除子孙
                $childIds = $this->getAllChild($id);
                if ($childIds) {
                    $this->where($this->getPk(), 'in', $childIds)->delete();
                }
            }
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = '删除失败';
            $this->rollback();
            return false;
        }
    }

    /**
     * [delDatas 批量删除数据]
     * @linchuangbin
     * @DateTime  2017-02-11T20:59:34+0800
     * @param     array                   $ids    [主键数组]
     * @param     boolean                 $delSon [是否删除子孙数据]
     * @return    [type]                          [description]
     */
    public function delDatas($ids = [], $delSon = false)
    {
        if (empty($ids)) {
            $this->error = '删除失败';
            return false;
        }

        // 查找所有子元素
        if ($delSon) {
            foreach ($ids as $k => $v) {
                if (!is_numeric($v)) {
                    continue;
                }

                $childIds = $this->getAllChild($v);
                $ids = array_merge($ids, $childIds);
            }
            $ids = array_unique($ids);
        }

        try {
            $this->where($this->getPk(), 'in', $ids)->delete();
            return true;
        } catch (\Exception $e) {
            $this->error = '操作失败';
            return false;
        }
    }

    /**
     * [enableDatas 批量启用、禁用]
     * @AuthorHTL
     * @DateTime  2017-02-11T21:01:58+0800
     * @param     string                   $ids    [主键数组]
     * @param     integer                  $status [状态1启用0禁用]
     * @param     [boolean]                $delSon [是否删除子孙数组]
     * @return    [type]                           [description]
     */
    public function enableDatas($ids = [], $status = 1, $delSon = false)
    {
        if (empty($ids)) {
            $this->error = '操作失败';
            return false;
        }

        // 查找所有子元素
        if ($delSon && $status === '0') {
            foreach ($ids as $k => $v) {
                $childIds = $this->getAllChild($v);
                $ids = array_merge($ids, $childIds);
            }
            $ids = array_unique($ids);
        }
        try {
            $this->where($this->getPk(), 'in', $ids)->setField('status', $status);
            return true;
        } catch (\Exception $e) {
            $this->error = '操作失败';
            return false;
        }
    }

    /**
     * 获取所有子孙
     */
    public function getAllChild($id, &$data = [])
    {
        $map['pid'] = $id;
        $childIds = $this->where($map)->column($this->getPk());
        if (!empty($childIds)) {
            foreach ($childIds as $v) {
                $data[] = $v;
                $this->getAllChild($v, $data);
            }
        }
        return $data;
    }
}
